package kk.learn.rabbitmq.dlxdemo.service;

import kk.learn.rabbitmq.dlxdemo.model.Order;
import kk.learn.rabbitmq.dlxdemo.repository.OrderRepository;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


/**
 * <p>
 *
 * </p>
 *
 * @author KK
 * @since 2021-10-30
 */
@Service
public class OrderServiceImpl implements IOrderService {




    private final AmqpTemplate rabbitTemplate;
    private final OrderRepository orderRepository;



    public OrderServiceImpl(AmqpTemplate rabbitTemplate, OrderRepository orderRepository) {
        this.rabbitTemplate = rabbitTemplate;
        this.orderRepository = orderRepository;
    }


    @Override
    public Long order(Long userId, String product) {
        // 创建订单的状态为待支付;
        Order order = new Order();


        order.setProduct(product);
        order.setStatus("unpaid");
        order.setUserId(userId);
        order = orderRepository.save(order);


        // 发送一条消息到q.order队列中;
        rabbitTemplate.convertAndSend("ex.order", "order", order.getId());


        return order.getId();
    }

    @Transactional
    @Override
    public String pay(Long userId, Long orderId) {
        // 检查订单状态是否超时,
        final Order order = orderRepository.getOne(orderId);
        if (order == null){
            return null;
        }

        //​ 未超时, 修改为支付状态;
        if ("unpaid".equals(order.getStatus())){
            order.setStatus("paid");
            orderRepository.save(order);
            return "OK";
        }else{
            //​ 超时, 跳转到历史订单页面;
            return order.getStatus();
        }

    }

    @Override
    public List<Order> orders(Long userId) {
        // 返回历史订单
        return orderRepository.findOrdersByUserId(userId);
    }

    @Transactional
    @Override
    public void checkOrderStatus(Long orderId) {
        // 检查订单状态, 如果还是待支付, 更改状态未支付超时.

        final Order order = orderRepository.getOne(orderId);
        if ("unpaid".equals(order.getStatus())){
            System.out.println("发现订单超时， 超时的订单id： " + orderId);
            order.setStatus("overtime");
            orderRepository.save(order);
        }


    }
}
